package com.java.dao.impl;

import java.sql.*;

/**
 * TODO
 *
 * @author 村头老杨头
 * @version 1.0
 * @date 2021/9/26 16:48
 */
public class StudentDaoImpl {
    private String driver = "com.mysql.cj.jdbc.Driver";
    private String url = "jdbc:mysql://127.0.0.1:3306/edu";
    private String username = "root";
    private String password = "123456";
    //    模拟用户登录 注入攻击
    public void login(String sname,String sno) throws ClassNotFoundException, SQLException {
        //加载驱动
        Class.forName(driver);
        //创建连接
        Connection conn = DriverManager.getConnection(url, username, password);
        //创建Statement
        String sql = "select * from student where sname='"+sname+"' and sno="+sno;
        System.out.println(sql);
        Statement st = conn.createStatement();
        //发送SQL语句并返回结果集
        //  select * from student where sname='张三' and sno=112 or 1=1
        ResultSet rs = st.executeQuery(sql);
        //解析结果集
        if(rs.next()){
            System.out.println("登录成功");
        }else{
            System.out.println("登录失败");
        }
        //关闭资源
        rs.close();
        st.close();
        conn.close();
    }
    //    模拟用户登录  防止SQL注入攻击
    public void login1(String sname,String sno) throws ClassNotFoundException, SQLException {
        //加载驱动
        Class.forName(driver);
        //创建连接
        Connection conn = DriverManager.getConnection(url, username, password);
        //创建Statement
        //把SQL中的参数换成占位符 ?
        String sql = "select * from student where sname=? and sno=?";
        //SQL预处理   预编译
        PreparedStatement ps = conn.prepareStatement(sql);
        //填充问号
        ps.setObject(1,sname);
        ps.setObject(2,sno);
        //发送SQL语句并返回结果集
        // select * from student where sname='张三' and sno='112 or 1=1';
        ResultSet rs = ps.executeQuery();
        //解析结果集
        if(rs.next()){
            System.out.println("登录成功");
        }else{
            System.out.println("登录失败");
        }
        //关闭资源
        rs.close();
        ps.close();
        conn.close();
    }
}
